package com.sh.caryr.erp.controller.user;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.sh.caryr.erp.entity.PageResultMessage;
import com.sh.caryr.erp.entity.ResultMessage;
import com.sh.caryr.erp.exception.ResultCode;
import com.sh.caryr.erp.entity.user.User;
import com.sh.caryr.erp.entity.user.UserRole;
import com.sh.caryr.erp.entity.user.UserRoleAuth;
import com.sh.caryr.erp.exception.RestServiceException;
import com.sh.caryr.erp.service.IUserRoleAuthService;
import com.sh.caryr.erp.service.IUserRoleService;
import com.sh.caryr.erp.util.ERPConstants;
import com.sh.caryr.erp.util.MyBatisUtil;
import com.sh.caryr.erp.util.UtilityTool;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户权限表 前端控制器
 * </p>
 *
 * @author milkeeper
 * @since 2017-12-10
 */
@RestController
@RequestMapping("/api/userRole")
@SessionAttributes("user")
public class UserRoleController {

    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IUserRoleAuthService roleAuthService;


    @ApiOperation(value = "获取权限列表信息,支持分页，支持多个查询条件（多个条件用','隔开），支持单个排序", notes = "获取权限列表信息")
    @RequestMapping(method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public PageResultMessage<List<UserRole>> findUserRoles(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String queryField,
            @RequestParam(required = false) String queryValue,
            @RequestParam(required = false) Boolean isAccurate,
            @RequestParam(defaultValue = "id") String orderBy,
            @RequestParam(defaultValue = "false") Boolean isAsc,
            @ModelAttribute("user") User operator) {

        Wrapper wrapper = MyBatisUtil.getIsActiveWrapper(queryField, queryValue, orderBy,isAsc);
        List<UserRole> userRoles = userRoleService.findUserRolesDynamic(current, size, wrapper, orderBy);
        MyBatisUtil.addAuthFilter(wrapper, operator, ERPConstants.AUTH_TARGET_USERROLE, false, false);
        return new PageResultMessage<>(userRoles, userRoleService.selectCount(wrapper));
    }


    @ApiOperation(value = "创建UserRole", notes = "创建UserRole")
    @ApiImplicitParam(name = "userRole", value = "详细实体userRole", required = true, dataType = "UserRole")
    @Transactional
    @RequestMapping(method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    public ResultMessage<String> insertUserRole(@RequestBody UserRole userRole, @ModelAttribute("user") User operator) {
        userRole.setCreateBy(operator.getId());
        userRole.setCoco(operator.getCoco());
        if (!userRoleService.insert(userRole)) {
            new RestServiceException(ResultCode.CREATE_FAILED);
        }
        List<UserRoleAuth> authList = userRole.getAuthList();
        for (UserRoleAuth auth : authList) {
            auth.setRoleId(userRole.getId());
        }
        if (authList != null && authList.size() != 0) {
            if (!roleAuthService.insertBatch(authList)) {
                new RestServiceException(ResultCode.CREATE_FAILED);
            }
        }
        return new ResultMessage<>(userRole.getId().toString());
    }


    @ApiOperation(value = "更新", notes = "更新")
    @ApiImplicitParam(name = "userRole", value = "实体", required = true, dataType = "UserRole")
    @Transactional
    @RequestMapping(method = RequestMethod.PUT)
    @ResponseStatus(HttpStatus.OK)
    public ResultMessage<UserRole> updateUserRoleById(@RequestBody UserRole userRole, @ModelAttribute("user") User operator) {
        userRole.setUpdateBy(operator.getId());
        userRole.setUpdateAt(new Date());
        if (!userRoleService.updateById(userRole)) {
            throw new RestServiceException(ResultCode.UPDATE_FAILED);
        }

        roleAuthService.delete(new EntityWrapper<UserRoleAuth>().eq("roleId", userRole.getId()));
        List<UserRoleAuth> authList = userRole.getAuthList();
        for (UserRoleAuth auth : authList) {
            auth.setRoleId(userRole.getId());
        }
        if (authList != null && authList.size() != 0) {
            if (!roleAuthService.insertBatch(authList)) {
                new RestServiceException(ResultCode.CREATE_FAILED);
            }
        }
        return new ResultMessage<>(userRole);
    }


    @ApiOperation(value = "批量UserRole", notes = "根据url的id来指定删除对象")
    @ApiImplicitParam(name = "ids", value = "UserRole IDS", required = true, dataType = "String")
    @Transactional
    @RequestMapping(value = "/{ids}", method = RequestMethod.DELETE)
    @ResponseStatus(HttpStatus.OK)
    public ResultMessage deleteUserRoleById(@PathVariable String ids) {
        List<Long> list = UtilityTool.convertStringArray2LongList(ids.split(","));
        try {
            UtilityTool.softDelete(UserRole.class, list, userRoleService);
            return new ResultMessage();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RestServiceException(ResultCode.DELETE_NOT_FOUND);
        }
    }
}
